'use strict'

import axios from 'axios'
import qs from 'qs'
import { Indicator } from 'mint-ui'

axios.defaults.timeout = 3000;//设置请求超时时长
axios.defaults.retry = 2;//回调请求次数
axios.defaults.retryDelay = 1000;//请求间隔时间

axios.interceptors.request.use(config => {
    Indicator.open();
    return config
}, error => {
    Indicator.close();
    return Promise.reject(error)
})

axios.interceptors.response.use(response => {
    Indicator.close();
    return response
}, err => {
   
    var config = err.config;
    // If config does not exist or the retry option is not set, reject
    if(!config || !config.retry) return Promise.reject(err);
    
    // Set the variable for keeping track of the retry count
    config.__retryCount = config.__retryCount || 0;
    
    // Check if we've maxed out the total number of retries
    if(config.__retryCount >= config.retry) {
        // Reject with the error
        return Promise.reject(err);
    }
    
    // Increase the retry count
    config.__retryCount += 1;
    
    // Create new promise to handle exponential backoff
    var backoff = new Promise(function(resolve) {
        setTimeout(function() {
            resolve();
        }, config.retryDelay || 1);
    });
    // Return the promise in which recalls axios to retry the request
    return backoff.then(function() {
        return axios(config);
    });
    Indicator.close();
    // return Promise.resolve(error.response)
})
  
export function _http(url, options) {
    return new Promise((resolve,reject) => {
        var opt = options;
        axios({
          method: opt.type || 'post',
          url: url,
          params: opt.params || {},
          data: opt.data ? qs.stringify(opt.data)+'&time='+Math.round(Math.random()*10)*(new Date().getTime()) : {},
          headers: opt.headers || {'Content-Type': 'application/x-www-form-urlencoded'},
        //   headers:{'X-SID':realMd5,'X-DID':'1','X-RTIME':Math.round(new Date().getTime()/1000),'X-SIGN':'1','X-UA':'1','X-AGENT':'1','X-CORS':'1','Content-Type': 'application/x-www-form-urlencoded'}
        })
          .then(response => {
                resolve(response.data)
          }).catch(err =>{
                console.log(err)
          reject(err)
        })
      })
}
